package com.kitty.game.equip.handler;

import static com.kitty.game.utils.Const.MONEY_NAME;
import static com.kitty.game.utils.Const.ROLE_RESOURCE_NOT_ENOUGH;

import com.kitty.game.config.Equip;
import com.kitty.game.enter.RespGeneralNotify;
import com.kitty.game.equip.EquipDataPool;
import com.kitty.game.equip.message.RespHunQiFenHuaRes;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.HunQiAttrField;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.role.model.Role;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.NotifyModules;
import com.kitty.game.utils.StringUtil;
import com.kitty.mina.message.MessagePusher;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import lombok.extern.slf4j.Slf4j;
import org.nutz.json.Json;
import org.nutz.lang.random.R;
import org.springframework.stereotype.Component;
import com.kitty.game.equip.handler.UpgradeHandler;

/**
 * 魂器 两级分化
 */
@Component("EquipHunQiFenHuaHandler")
@Slf4j
public class EquipHunQiFenHuaHandler extends UpgradeHandler {

    public static final String EXCEPTION = "失败";

    public static final Short[] ATTRS_YANG = {
            2, 3, 9, 10, 13,
            14, 67, 78, 117,
            126, 127, 128, 129, 130,
            131, 132, 133, 134, 135,
            168, 169
    };

    public static final Integer[] MAX_ATTR_YANG = {
            50, 1000, 50, 1000, 50,
            400, 10, 30, 30,
            30, 30, 30, 30, 30,
            30, 30, 30, 30, 30,
            30, 30};

    public static final Short[] ATTRS_YIN = {
            5, 7, 8, 12, 50,
            51, 52, 53, 54, 56,
            57, 58, 59, 60, 69,
            77, 80, 85, 222, 223,
    };

    public static final Integer[] MAX_ATTR_YIN = {
            50, 2000, 2000, 2000, 30,
            30, 30, 30, 30, 30,
            30, 30, 30, 30, 10,
            30, 20, 30, 30, 30};

    /**
     * 炼化成功提示
     */
    private static final String REFINE_SUCCESS = "恭喜你，炼化成功。";

    /**
     * 炼化失败提示
     */
    private static final String REFINE_FAIL = "真遗憾，炼化失败了。";

    private static final Short ATTR_TYPE = 260;
    private HashMap<Short,Integer> yang_value = new HashMap();
    private HashMap<Short,Integer> yin_value = new HashMap();

    public void init(){
        for (int i=0;i<ATTRS_YANG.length;i++){
            yang_value.put(ATTRS_YANG[i],MAX_ATTR_YANG[i]);
        }

        for (int i=0;i<ATTRS_YIN.length;i++){
            yin_value.put(ATTRS_YIN[i],MAX_ATTR_YIN[i]);
        }
    }

    @Override
    public String doUpgrade(Role role, Object... params) {
        RoleEquip roleEquip = (RoleEquip) params[0];
        String param = (String) params[1];
        Equip equip = (Equip) params[2];

        Random random = ThreadLocalRandom.current();
        String[] split = param.split("\\|");
        boolean success = true;

        /**扣钱*/
        int cash = needCash(roleEquip.queryLevel(), 0);
        roleService.subtractMoney(role, cash);

        if (success) {
            /**获得随机属性*/
            int pos = Byte.parseByte(split[0]);
            log.error("魂器属性位置=={}",pos);
            HunQiAttrField attrField = roleEquip.getHunQiFields().get(ATTR_TYPE).getField().get(pos - 1);
            //阴阳rate不超过70
            int rate = random.nextInt(40) + 30;
            attrField.setYangRate((byte) rate);

            //生成阳属性
            {
                int index = -1;
                do {
                    index = random.nextInt(ATTRS_YANG.length);
                } while (checkExist(roleEquip, ATTRS_YANG[index]));

                String attrName = EquipDataPool.id2Attribute.get(ATTRS_YANG[index]).getName();
                int val = (int) Math.round(MAX_ATTR_YANG[index] * attrField.queryYang() * 0.01) + 1;
                attrField.setYangAttrName(attrName);
                attrField.setYangAttrVal((short) val);
                if(val>66){
                    roleService.addAchieveScore(role,"304005");
                }
            }

            {
                int index = -1;
                do {
                    index = random.nextInt(ATTRS_YIN.length);
                } while (checkExist(roleEquip, ATTRS_YIN[index]));

                String attrName = EquipDataPool.id2Attribute.get(ATTRS_YIN[index]).getName();
                int val = (int) Math.round(MAX_ATTR_YIN[index] * attrField.queryYang() * 0.01) + 1;
                attrField.setYinAttrName(attrName);
                attrField.setYinAttrVal((short) val);
                if(val>66){
                    roleService.addAchieveScore(role,"304005");
                }
            }

            refreshRoleEquip(role, roleEquip);
            //不计算完美度
            //equipService.countPerfect(roleEquip);
            RespGeneralNotify respGeneralNotify = new RespGeneralNotify();
            respGeneralNotify.setValue(roleEquip.getId() + "");
            respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_EQUIP_REFINE_OK);//炼化成功
            MessagePusher.pushMessage(role, respGeneralNotify);
            roleService.addAchieveScore(role,"304001");
            RespHunQiFenHuaRes hunQiFenHuaRes = new RespHunQiFenHuaRes();
            hunQiFenHuaRes.setBackpackPos(roleEquip.getPosition());
            hunQiFenHuaRes.setPos((byte) pos);
            hunQiFenHuaRes.setYang((byte) attrField.queryYang());
            hunQiFenHuaRes.setYin((byte) attrField.queryYin());
            MessagePusher.pushMessage(role, hunQiFenHuaRes);

            return REFINE_SUCCESS;
        } else {
            return REFINE_FAIL;
        }
    }

    @Override
    public String acceptUpgrade(Role role, int upgradePos, String param) {
        RoleEquip roleEquip = equipService.getRoleEquipByPos(role, upgradePos);
        if (roleEquip == null) {
            return "请放入正确的装备。";
        }
        if (!isRightPosition(roleEquip.queryEquipPos(false))) {
            return MessageFormat.format(NO_RIGHT_POSITION, "两仪分化", roleEquip.getName());
        }
        Equip equip = EquipDataPool.getByName(roleEquip.getName());
        if (equip == null) {
            log.error("找不到装备配置ICON=[{}]", upgradePos);
            return MessageFormat.format(NOT_FIND_CONFIG, roleEquip.getName());
        }

        String noEnough = checkResource(role, param, roleEquip);
        if (noEnough != null) {
            return noEnough;
        }

        return doUpgrade(role, roleEquip, param, equip);
    }

    @Override
    public String checkResource(Object... objects) {
        Role role = (Role) objects[0];
        String param = (String) objects[1];
        RoleEquip roleEquip = (RoleEquip) objects[2];

        int pos = Integer.parseInt(param);
        if (!roleEquip.getName().startsWith("魂器")) {
            return EXCEPTION;
        }

        if (needCash((short) 0, 0) > role.getMoney()) {
            return MessageFormat.format(ROLE_RESOURCE_NOT_ENOUGH, MONEY_NAME);
        }

        HunQiAttrField attrField = roleEquip.getHunQiFields().get(ATTR_TYPE).getField().get(pos - 1);
        //如果未混沌
        if (attrField.getHunDun() <= 0) {
            return EXCEPTION;
        }

        return null;
    }


    public boolean checkExist(RoleEquip roleEquip, short attrId) {
        List<HunQiAttrField> attrs = roleEquip.getHunQiFields().get(ATTR_TYPE).getField();
        int count = 0;
        for (int i = 0; i < 5; i++) {
            HunQiAttrField field = attrs.get(i);
            //比较阳
            if (!StringUtil.isEmpty(field.getYangAttrName())) {
                if (EquipDataPool.name2AttribId.getOrDefault(field.getYangAttrName(), (short) 0) == attrId) {
                    count++;
                }
            }

            if (!StringUtil.isEmpty(field.getYinAttrName())) {
                if (EquipDataPool.name2AttribId.getOrDefault(field.getYinAttrName(), (short) 0) == attrId) {
                    count++;
                }
            }
        }

        //最多出现2条一样 就不再生成这个了
        return count > 1;
    }

    @Override
    public int needCash(short level, int pos) {
        return 200000;
    }

    @Override
    public String getUpdateTypeStr() {
        return "hun_qi_fen_hua";
    }


    public void addHunqi(Role role,String content){
        // @@hunqi==澹台膪逶==魂器·锋芒(灵力=20=气血。灵力=20=气血。敏捷=20=防御。敏捷=20=防御。速度=20=法力)
        // 物伤  法伤  速度   力量   灵力   敏捷
        short newPos = bagService.getPos(role, false);
        if (newPos <= 0) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你的包裹已满。"));
            return;
        }
        String equipName = content.substring(0,content.indexOf("("));
        Equip equip = EquipDataPool.getByName(equipName);
        if (equip == null){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("魂器不存在。"));
            return;
        }
        HashMap<String,Short> hashMap = new HashMap<>();
        hashMap.put("灵力", (short) 9);
        hashMap.put("敏捷", (short) 13);
        hashMap.put("速度", (short) 14);
        hashMap.put("力量", (short) 2);
        hashMap.put("法伤", (short) 10);
        hashMap.put("物伤", (short) 3);
        hashMap.put("忽视所有抗异常", (short) 169);

        hashMap.put("气血", (short) 7);
        hashMap.put("防御", (short) 8);
        hashMap.put("法力", (short) 12);
        int ii = content.indexOf("(");
        String attStr = content.substring(ii+1,content.length()-1);
        String[] tempp = attStr.split("##");
        short[] yins = {7,7,8,8,12};
        short[] yangs = {9,10,13,3,14};
//        int[] yang_value = new int[5];
//        HashMap<Short,Integer> att_value = new HashMap<>();
        int j =0;
        for (String ss : tempp){
            String[] aa = ss.split("=");
            yangs[j] = hashMap.get(aa[0]);
            yins[j] = hashMap.get(aa[1]);
//            yang_value[j] = Integer.parseInt(aa[1]);
            j++;
        }
        log.error(attStr);
        RoleEquip roleEquip = equipService.getHunQi(equip, role, newPos);
        for (int i=1;i<=5;i++){
            int pos = i;
//            logger.error("魂器属性位置=={}",pos);
            HunQiAttrField attrField = roleEquip.getHunQiFields().get(ATTR_TYPE).getField().get(pos - 1);
            attrField.setHunDun((byte) 100);
            //阴阳rate不超过70
//            int rate = 69;
            attrField.setYangRate((byte) 70);

            //生成阳属性
            {
                short attId = yangs[i-1];
                String attrName = EquipDataPool.id2Attribute.get(attId).getName();
                int val = yang_value.get(attId);
                attrField.setYangAttrName(attrName);
                attrField.setYangAttrVal((short) val);
            }

            {
                short attId = yins[i-1];
                String attrName = EquipDataPool.id2Attribute.get(attId).getName();
                int val = yin_value.get(attId);
                attrField.setYinAttrName(attrName);
                attrField.setYinAttrVal((short) val);
            }
//            logger.error("属性值=={}=={}", Json.toJson(attrField),attrField.toString());
            RespGeneralNotify respGeneralNotify = new RespGeneralNotify();
            respGeneralNotify.setValue(roleEquip.getId() + "");
            respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_EQUIP_REFINE_OK);//炼化成功
            MessagePusher.pushMessage(role, respGeneralNotify);

            RespHunQiFenHuaRes hunQiFenHuaRes = new RespHunQiFenHuaRes();
            hunQiFenHuaRes.setBackpackPos(roleEquip.getPosition());
            hunQiFenHuaRes.setPos((byte) pos);
            hunQiFenHuaRes.setYang((byte) attrField.queryYang());
            hunQiFenHuaRes.setYin((byte) attrField.queryYin());
            MessagePusher.pushMessage(role, hunQiFenHuaRes);

            //不计算完美度
            //equipService.countPerfect(roleEquip);
        }
        refreshRoleEquip(role, roleEquip);
        log.error("命令添加魂器=={}=={}=={}",role.getRoleId(),role.getName(),content);
    }
}
